import router, { asyncRoutes } from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  if (store.getters.token) {
    // 存在token
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      // 获取用户资料
      if (!store.getters.userId) {
        // 从个人信息中获取用户的路由权限
        const { roles } = await store.dispatch('user/getUserInfo')
        console.log('用户路由权限：', roles)
        // 1. 遍历动态路由
        // 2. 过滤出当前用户有权限的路由
        // 3. 添加动态路由
        const filterRoutes = asyncRoutes.filter(item => {
          return roles.menus.includes(item.name)
        })
        // console.log('过滤后的路由：', filterRoutes)
        // 404页面 放在最后面
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        // 提交mutation 更新routes
        store.commit('user/setRoutes', filterRoutes)
        // router添加动态路由之后 需要转发一下
        // 目的是让路由拥有信息 - vue-router3.x 的已知缺陷(刷新后白屏)
        next(to.path)
      }
      next()
    }
  } else {
    // 没有token
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
